﻿using Bird.OAWeb.WebAPI.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Diagnostics;

namespace Bird.OAWeb.WebAPI.Filters
{
    public class OAWebAsyncActionFilter : IAsyncActionFilter
    {
        private readonly ILogger<OAWebAsyncActionFilter> _logger;
        /// <summary>
        /// 构造函数 注入依赖
        /// </summary>
        /// <param name="logger"></param>
        public OAWebAsyncActionFilter(ILogger<OAWebAsyncActionFilter> logger)
        {
            _logger = logger;
        }
        public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //判断当前的方法上面有没有[NoLog]这个特性标注，有的话，则不记录日志信息
            if (context.ActionDescriptor.EndpointMetadata.Any(x => x.GetType() == typeof(NoLogAttribute)))
            {
                return next();
            }
            //Stopwatch 这个类是一个秒表，可以统计所用的时间
            Stopwatch sw = new Stopwatch();
            sw.Start();  //开始计时
            next();  //调用执行action方法
            sw.Stop();  //停止计时
            long n = sw.ElapsedMilliseconds; //所用的毫秒数
            string message = DateTime.Now + "调用了" + context.HttpContext.Request.Path + "方法" + "用时了" + n + "毫秒";
            _logger.LogInformation(message);
            //完成任务
            return Task.CompletedTask;
        }
    }
}
